/**
 * Copyright (C), 2015-2019, XXX有限公司
 * FileName: ValidateCodeController
 * Author:   zhouheng
 * Date:     2019/6/7 23:21
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.zhouh.golden.web.controller.security;

import com.zhouh.golden.common.constants.GoldenConstant;
import com.zhouh.golden.common.domain.ResponseBo;
import com.zhouh.golden.security.code.ValidateCode;
import com.zhouh.golden.security.code.ValidateCodeGenerator;
import com.zhouh.golden.security.code.img.ImageCode;
import com.zhouh.golden.security.code.sms.SmsCode;
import com.zhouh.golden.security.code.sms.SmsCodeSender;
import com.zhouh.golden.web.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 〈一句话功能简述〉<br> 
 * 〈〉
 *
 * @author zhouheng
 * @create 2019/6/7
 * @since 1.0.0
 */
@Slf4j
@RestController
public class ValidateCodeController extends BaseController{
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    @Autowired
    private ValidateCodeGenerator imageCodeGenerator;
    @Autowired
    private ValidateCodeGenerator smsCodeGenerator;
    @Autowired
    private SmsCodeSender smsCodeSender;


    @GetMapping("/image/code")
    public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ImageCode imageCode = (ImageCode) imageCodeGenerator.createCode();
        BufferedImage image = imageCode.getImage();
        imageCode.setImage(null);
        sessionStrategy.setAttribute(new ServletWebRequest(request), GoldenConstant.SESSION_KEY_IMAGE_CODE, imageCode);
        response.setContentType("image/jpeg");
        ImageIO.write(image, "jpeg", response.getOutputStream());
    }

    @GetMapping("/sms/code")
    public ResponseBo createSmsCode(HttpServletRequest request, HttpServletResponse response, String mobile) {
        try {
            ValidateCode smsCode = smsCodeGenerator.createCode();
            sessionStrategy.setAttribute(new ServletWebRequest(request), GoldenConstant.SESSION_KEY_SMS_CODE + mobile, smsCode);

            // 发送短信
            smsCodeSender.send(mobile, smsCode.getCode());
            return ResponseBo.ok();
        } catch (Exception e) {
            log.error("短信验证码发送失败", e);
            return ResponseBo.error();
        }
    }
}